﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace Chenglin.W8Timer
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class CountDownScenario : LayoutAwarePage
    {
        public CountDownScenario()
        {
            this.InitializeComponent();

            this.CountdownPanel.ResetClick += delegate
            {
                this.SettingsPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.CountdownPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            };
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            StartLayoutUpdates(this.CountdownPanel, new RoutedEventArgs());
            base.OnNavigatedTo(e);
        }

        private void OnStartCountDown(object sender, RoutedEventArgs e)
        {
            int hours = 0, minutes = 0, seconds = 0;
            bool isValidSetting = false;
            if (int.TryParse(tbSettingHours.Text, out hours) && hours >= 0
                && int.TryParse(tbSettingMinutes.Text, out minutes) && minutes >= 0
                && int.TryParse(tbSettingSeconds.Text, out seconds) && seconds >= 0)
            {
                isValidSetting = hours > 0 || minutes > 0 || seconds > 0;
            }

            if (!isValidSetting)
            {
                tbError.Visibility = Windows.UI.Xaml.Visibility.Visible;
                tbError.Text = "ERROR: Invalid settings, please check again.";
            }
            else
            {
                tbError.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                TimeSpan ts = new TimeSpan(hours, minutes, seconds);

                this.CountdownPanel.StartTimer(true, ts);
                this.SettingsPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.CountdownPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
        }
    }
}
